﻿#region Copyright (c) 2007-2011 SmartVault Corporation, all rights reserved.
// 
// http://www.opensource.org/licenses/mit-license.php
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// 
#endregion
using System;
using System.Windows.Forms;
using Interop.SVault.Client.SDK;
using System.IO;
using Interop.SVault.Client.SDK.Utils;
using CRMStore;

namespace SampleClient
{
    public partial class Form1 : Form
    {
        private IApplicationContext _context;
        private IContextNewItem _newItem;
        private ICustomToolbar _Toolbar;
        private const string OurApplicationName = "SmartVault CRM Store Sample";

        public Form1()
        {
            InitializeComponent();

            this.SuspendLayout();
            InitSmartVaultToolBar();
            this.ResumeLayout(false);

        }

        private CRMDatabase Database
        {
            get { return CRMDatabaseLoader.Instance.Data; }
        }

        private void InitSmartVaultToolBar()
        {
            this._Toolbar = Activator.CreateInstance(Type.GetTypeFromProgID("SmartVault.Toolbar.1")) as ICustomToolbar;
            this._Toolbar.BackgroundColor = 16777215;
            this._Toolbar.BackgroundGradient = true;
            this._Toolbar.BackgroundGradientColor = 16777215;
            ((UserControl)this._Toolbar).Dock = System.Windows.Forms.DockStyle.Right;
            ((UserControl)this._Toolbar).Location = new System.Drawing.Point(626, 0);
            ((UserControl)this._Toolbar).Margin = new System.Windows.Forms.Padding(0);
            ((UserControl)this._Toolbar).MaximumSize = new System.Drawing.Size(58, 9999);
            ((UserControl)this._Toolbar).MinimumSize = new System.Drawing.Size(58, 50);
            ((UserControl)this._Toolbar).Name = "Toolbar";
            ((UserControl)this._Toolbar).Size = new System.Drawing.Size(58, 406);
            ((UserControl)this._Toolbar).TabIndex = 0;
            this.Controls.Add(this._Toolbar as Control);
        }

        protected override void OnShown(EventArgs e)
        {
            _context = Database.OpenToolbar(((ICustomToolbar)this._Toolbar));
            _context.Provision();

            lbItems.DisplayMember = "Display";
            lbItems.DataSource = Database.Customers;

            txtQBFile.Text = Database.QBDatabasePath;
            txtQBVerify.Text = Database.QBIdentifier;

            btnSync.Enabled = !string.IsNullOrEmpty(Database.QBIdentifier);

            base.OnShown(e);
            tabControl1_Selected(tabControl1.SelectedTab,
                                 new TabControlEventArgs(tabControl1.SelectedTab, tabControl1.SelectedIndex,
                                                         TabControlAction.Selected));
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            IContextMessage msg;
            switch (e.TabPage.Name)
            {
                case "tabHome":
                    msg = _context.CreateMessage();
                    msg.SetRecordType("Home");
                    msg.Commit();
                    break;
                case "tabItem":
                    lbItems_SelectedIndexChanged(this, EventArgs.Empty);
                    break;
                case "tabNew":
                    msg = _context.CreateMessage();
                    _newItem = msg.SetNewItem(Customer.StaticObjectType);
                    msg.Commit();
                    btnDiscard.Enabled = btnCreate.Enabled = txtFirstName.Text.Length > 0 && txtLastName.Text.Length > 0 && _context.AssociationState == ContextAssociationState.ContextAssociated;
                    break;
                case "tabNone":
                    _context.ClearCurrentItem();
                    break;
            }
        }

        private void lbItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            IContextMessage msg;
            if (lbItems.SelectedIndex < 0)
            {
                _context.ClearCurrentItem();
                btnDelete.Enabled = false;
            }
            else
            {
                btnDelete.Enabled = true;
                msg = _context.CreateMessage();

                Record r = (Record)lbItems.Items[lbItems.SelectedIndex];

                msg.SetRecordTypeWithId(r.ObjectType, r.Id.ToString());
                msg.Commit();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lbItems.SelectedIndex >= 0)
            {
                Record r = (Record)lbItems.Items[lbItems.SelectedIndex];
                Database.RemoveCustomer(r.Id);
                lbItems.SelectedIndex = -1;
                lbItems.DataSource = lbItems.DataSource;
            }
        }

        private void NameTextChanged(object sender, EventArgs e)
        {
            btnDiscard.Enabled = btnCreate.Enabled = txtFirstName.Text.Length > 0 && txtLastName.Text.Length > 0 && _context.AssociationState == ContextAssociationState.ContextAssociated;
        }

        private void NameTextChanged(object sender, KeyEventArgs e)
        { NameTextChanged(sender, EventArgs.Empty); }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            Customer c = new Customer(txtFirstName.Text.Trim(), txtLastName.Text.Trim());
            Database.Customers.Add(c);

            _newItem.Commit(c.Id.ToString());

            lbItems.SelectedItem = c;
            lbItems.DataSource = lbItems.DataSource;
            tabControl1.SelectedTab = tabItem;
        }

        private void btnDiscard_Click(object sender, EventArgs e)
        {
            _newItem.AbandonItem();
            txtFirstName.Text = txtLastName.Text = String.Empty;
            tabControl1.SelectedTab = tabItem;
        }

        private void btnQBFileBrowser_Click(object sender, EventArgs e)
        {
            
            OpenFileDialog open = new OpenFileDialog();
            if (open.ShowDialog() == DialogResult.OK)
            {
                txtQBFile.Text = open.FileName;
            }
        }

        private void btnCheckQB_Click(object sender, EventArgs e)
        {
            try
            {
                ISmartVaultClientUtils sdkUtils = CRMDatabase.CreateClientUtils();
                ISmartVaultQBDataAccess qbDataAccess = null;

                qbDataAccess = sdkUtils.CreateQBDataAccess(txtQBFile.Text, OurApplicationName);

                txtQBVerify.Text = qbDataAccess.ApplicationId;

                Database.QBDatabasePath = txtQBFile.Text;
                Database.QBIdentifier = txtQBVerify.Text;
                Database.QBAppType = qbDataAccess.ApplicationType;

                ISmartVaultClientSDK sdk = CRMDatabase.GetSDK();

                IApplicationContext ctx = sdk.Open(CRMDatabaseLoader.Instance.Data.QBAppType,
                    Database.QBIdentifier, "Title");

                if (ctx.AssociationState == ContextAssociationState.ContextNotProvisioned)
                {
                    ctx.Provision();
                }

                provisionSibling.Enabled = ctx.AssociationState == ContextAssociationState.ContextAssociated;
            }
            catch (Exception error)
            {
                MessageBox.Show(this, error.Message);
            }
        }

        private void provisionSibling_Click(object sender, EventArgs e)
        {
            Database.ProvisionWithQB(_context);
        }

        private void txtQBFile_TextChanged(object sender, EventArgs e)
        {
            btnCheckQB.Enabled = File.Exists(txtQBFile.Text)
                && Path.GetExtension(txtQBFile.Text).ToLower() == ".qbw";
        }

        private void txtQBVerify_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtQBVerify.Text))
            {
                btnSync.Enabled = true;
            }
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            try
            {
                ISmartVaultClientSDK sdk = CRMDatabase.GetSDK();

                IApplicationContext ctx = sdk.Open(CRMDatabaseLoader.Instance.Data.QBAppType,
                    Database.QBIdentifier, "Title");

                if (ctx.AssociationState != ContextAssociationState.ContextAssociated)
                {
                    throw new Exception("QB Company Not Associated");
                }

                // we are now looking at home in the QB company
                IContextMessage message = ctx.CreateMessage();
                message.SetRecordType("Home");
                message.Commit();

                IContextDocumentList destinationLst = ctx.ContextState.GetDocuments();

                if (!destinationLst.CanAttach)
                {
                    throw new Exception("Cannot copy to home. Access Denied.");
                }

                IContextDocumentList lst = _context.ContextState.GetDocuments();

                for (int i = 0; i < lst.Count; ++i)
                {
                    IContextDocument doc = lst.TryGetByOrdinal(i);

                    if (doc != null)
                    {
                        if (!CRMDatabaseLoader.Instance.Data.IsHomeSynced(doc.Id) &&
                            doc.DocumentState == DocumentState.DocumentAvailable)
                        {
                            destinationLst.CopyDocumentHere(doc);
                            CRMDatabaseLoader.Instance.Data.MarkSynced(doc.Id);
                        }
                    }
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(this, error.Message);
            }
        }

        private void btnAttachOnline_Click(object sender, EventArgs e)
        {
            OnlineAttachment attach = new OnlineAttachment();

            DialogResult result = attach.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                txtDownloadUrl.Text = attach.DownloadUrl;
            }
            else
            {
                txtDownloadUrl.Text = string.Empty;
            }
        }
    }
}
